/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Formulario_imovel.java
 *
 * Created on 11/06/2011, 14:35:24
 */

package formularios;

import formularios.model.Construtoras;
import formularios.model.Imoveis;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Ramon
 */
public class Formulario_imovel extends javax.swing.JInternalFrame {

    /** Creates new form Formulario_imovel */
    public Formulario_imovel() {

        initComponents();
        //quando apertar enter, o botão salvar será acionado
        getRootPane().setDefaultButton(btn_imovel_salvar);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        radGroup_imovel_tipo = new javax.swing.ButtonGroup();
        radGroup_imovel_vendido = new javax.swing.ButtonGroup();
        lab_imovel_cod = new javax.swing.JLabel();
        lab_imovel_cnpj_const = new javax.swing.JLabel();
        lab_imovel_condominio = new javax.swing.JLabel();
        lab_imovel_area_util = new javax.swing.JLabel();
        lab_imovel_preco = new javax.swing.JLabel();
        lab_imovel_tipo = new javax.swing.JLabel();
        lab_imovel_vendido = new javax.swing.JLabel();
        txt_imovel_cod = new formularios.IntTextField();
        try {
            MaskFormatter formato_cnpj = new MaskFormatter("##.###.###/####-##");
            txt_imovel_cnpj_const = new  JFormattedTextField(formato_cnpj);
            txt_imovel_condominio = new javax.swing.JTextField();
            txt_imovel_area_util = new javax.swing.JTextField();
            txt_imovel_preco = new MoedaTextField();
            rad_imovel_apart = new javax.swing.JRadioButton();
            rad_imovel_casa = new javax.swing.JRadioButton();
            rad_imovel_sim = new javax.swing.JRadioButton();
            rad_imovel_nao = new javax.swing.JRadioButton();
            btn_imovel_salvar = new javax.swing.JButton();
            btn_imovel_limpar = new javax.swing.JButton();
            btn_imovel_excluir = new javax.swing.JToggleButton();

            setClosable(true);
            setIconifiable(true);
            setMaximizable(true);
            setResizable(true);
            setTitle("Formulário de Imóvel");

            lab_imovel_cod.setText("Código do Imóvel");

            lab_imovel_cnpj_const.setText("CNPJ da Construtora");

            lab_imovel_condominio.setText("Nome do Condomínio");

            lab_imovel_area_util.setText("Área útil");

            lab_imovel_preco.setText("Preço");

            lab_imovel_tipo.setText("Tipo de imóvel");

            lab_imovel_vendido.setText("Vendido");

            txt_imovel_cod.addFocusListener(new java.awt.event.FocusAdapter() {
                public void focusLost(java.awt.event.FocusEvent evt) {
                    txt_imovel_codFocusLost(evt);
                }
            });

        } catch (ParseException ex) {
            Logger.getLogger(Formulario_empregado.class.getName()).log(Level.SEVERE, null, ex);
        }

        radGroup_imovel_tipo.add(rad_imovel_apart);
        rad_imovel_apart.setText("Apartamento");

        radGroup_imovel_tipo.add(rad_imovel_casa);
        rad_imovel_casa.setText("Casa");

        radGroup_imovel_vendido.add(rad_imovel_sim);
        rad_imovel_sim.setText("Sim");

        radGroup_imovel_vendido.add(rad_imovel_nao);
        rad_imovel_nao.setText("Não");

        btn_imovel_salvar.setText("Salvar");
        btn_imovel_salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_imovel_salvarActionPerformed(evt);
            }
        });

        btn_imovel_limpar.setText("LImpar");
        btn_imovel_limpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_imovel_limparActionPerformed(evt);
            }
        });

        btn_imovel_excluir.setText("Excluir");
        btn_imovel_excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_imovel_excluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(lab_imovel_cod)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(txt_imovel_cod, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(lab_imovel_condominio)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txt_imovel_condominio, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(62, 62, 62)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lab_imovel_tipo)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(30, 30, 30)
                                        .addComponent(lab_imovel_vendido))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_imovel_area_util)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_imovel_area_util, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_imovel_cnpj_const)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_imovel_cnpj_const, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rad_imovel_nao)
                            .addComponent(rad_imovel_sim)
                            .addComponent(rad_imovel_casa)
                            .addComponent(rad_imovel_apart))
                        .addContainerGap(53, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lab_imovel_preco)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_imovel_preco, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE)
                        .addComponent(btn_imovel_salvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_imovel_excluir)
                        .addGap(26, 26, 26)
                        .addComponent(btn_imovel_limpar)
                        .addGap(79, 79, 79))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_imovel_cod)
                            .addComponent(txt_imovel_cod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_imovel_cnpj_const)
                            .addComponent(txt_imovel_cnpj_const, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_imovel_condominio)
                            .addComponent(txt_imovel_condominio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(30, 30, 30))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_imovel_tipo)
                            .addComponent(rad_imovel_apart))
                        .addGap(5, 5, 5)
                        .addComponent(rad_imovel_casa)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_imovel_vendido)
                            .addComponent(rad_imovel_sim))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rad_imovel_nao)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btn_imovel_limpar)
                            .addComponent(btn_imovel_salvar)
                            .addComponent(btn_imovel_excluir))
                        .addGap(28, 28, 28))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_imovel_preco)
                            .addComponent(txt_imovel_preco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(116, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lab_imovel_area_util)
                    .addComponent(txt_imovel_area_util, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(77, 77, 77))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_imovel_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_imovel_salvarActionPerformed

        String tipo_imovel = "";
        char vendido = 0;
        String preco = "";

         //cria uma instancia relacionada ao contexto de persistencia
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
        EntityManager em = emf.createEntityManager();
        //cria uma instancia para controlar a transação
        EntityTransaction trans = em.getTransaction();

        //vefirica qual tipo de imovel está selecionado
        if(rad_imovel_apart.isSelected())
            tipo_imovel = rad_imovel_apart.getText();
        else if(rad_imovel_casa.isSelected())
            tipo_imovel = rad_imovel_casa.getText();

        //vefirifa se o imóvel está marcado como vendido ou não
        if(rad_imovel_sim.isSelected())
            vendido = 'S';
        else if(rad_imovel_sim.isSelected())
            vendido = 'N';

        //muda a String preco para ser possível transformá-la em double
        preco = txt_imovel_preco.getText();
        preco = preco.replace(".", "");
        preco = preco.replaceAll(",", ".");

        //busca a construtora que possui CNPJ digitado
        Construtoras cons = em.find(Construtoras.class, txt_imovel_cnpj_const.getText());

        //mensagem caso não exista nenhuma construtora com o CNPJ digitado
        if(cons == null)
        {
            JOptionPane.showMessageDialog(this, "Construtora não encontrada.");
            return;
        }

        //instancia do objeto Imoveis
        Imoveis imovel = new Imoveis(Integer.parseInt(txt_imovel_cod.getText()),
                                     cons,
                                     txt_imovel_condominio.getText(),
                                     txt_imovel_area_util.getText(),
                                     Double.parseDouble(preco), tipo_imovel, vendido);

        try {
            //insere ou atualiza um imovel
            trans.begin();
            em.merge(imovel);
            trans.commit();
            JOptionPane.showMessageDialog(this, "Imóvel cadastrado com sucesso.");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao inserir. Por favor, confira os dados.");
        }

        //encerra a transação
        em.close();
        emf.close();
    }//GEN-LAST:event_btn_imovel_salvarActionPerformed

    private void btn_imovel_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_imovel_excluirActionPerformed

        //verifica se existe algum código digitado
        if(txt_imovel_cod.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Entre com o código da construtora para excluí-la.");
            txt_imovel_cod.requestFocus();
        }else
        {
            //cria gerenciador do BancoImobiliaria
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
            EntityManager em = emf.createEntityManager();

            //a procura só será feita se existir um código digitado
            if(!txt_imovel_cod.getText().equals(""))
            {
                //procura o imóvel com o código digitado
                Imoveis imovel = em.find(Imoveis.class, Integer.parseInt(txt_imovel_cod.getText()));

                //verifica se o imóvel existe
                if(imovel == null) {
                    JOptionPane.showMessageDialog(this, "Código do imóvel não encontrado. Entre com o código correto.");
                    txt_imovel_cod.requestFocus();
                }else
                {
                    //mensagem de alerda da exclusão do imóvel
                    if (JOptionPane.showConfirmDialog(this,
                            "Esta operação não poderá ser desfeita.\n Deseja continuar?",
                            "Aviso",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)
                        return;                 

                    //só exclui o imóvel se ele já foi vendido
                    if(imovel.getVendido() == 'S')
                    {
                        //obtem uma transação
                        EntityTransaction trans = em.getTransaction();

                        //remove imóvel
                        trans.begin();
                        em.remove(imovel);
                        trans.commit();

                        //encerra a transação
                        em.close();
                        emf.close();

                        limparCampos();
                    }else if(imovel.getVendido() == 'N')
                        JOptionPane.showMessageDialog(this, "Exclusão negada. Este imóvel ainda não foi vendido.");
                }
            }
        }
    }//GEN-LAST:event_btn_imovel_excluirActionPerformed

    private void btn_imovel_limparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_imovel_limparActionPerformed

        limparCampos();
    }//GEN-LAST:event_btn_imovel_limparActionPerformed

    private void txt_imovel_codFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txt_imovel_codFocusLost

        //cria gerenciador do BancoImobiliaria
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
        EntityManager em = emf.createEntityManager();

        //a procura só será feita se existir um código digitado
        if(!txt_imovel_cod.getText().equals(""))
        {
            //procura o imóvel com o código digitado
            Imoveis imovel = em.find(Imoveis.class, Integer.parseInt(txt_imovel_cod.getText()));

            //se o Objeto imovel existir, mostra seus dados
            if(imovel != null) {
                txt_imovel_cod.setText(Integer.toString(imovel.getCod()));
                txt_imovel_cnpj_const.setText(imovel.getConstrutoras().getCnpj());
                txt_imovel_condominio.setText(imovel.getNomeCondominio());
                txt_imovel_area_util.setText(imovel.getAreaUtil());

                //verifica qual tipo de imóvel está selecionado
                if(imovel.getTipoImovel().equals(rad_imovel_apart.getText()))
                    rad_imovel_apart.setSelected(true);
                else if(imovel.getTipoImovel().equals(rad_imovel_casa.getText()))
                    rad_imovel_casa.setSelected(true);

                 //verifica se o imovel está como vendido ou não
                if(imovel.getVendido() == 'S')
                    rad_imovel_sim.setSelected(true);
                else if(imovel.getVendido() == 'N')
                    rad_imovel_nao.setSelected(true);

                //máscara para moeda em real
                Locale brasil = new Locale("pt","BR");
                DecimalFormatSymbols real = new DecimalFormatSymbols(brasil);
                DecimalFormat dinheiro_real = new DecimalFormat("###,###,##0.00",real);

                //mostra o preco com a máscara da moeda real
                txt_imovel_preco.setText(dinheiro_real.format(imovel.getPreco()));

                //encerra a trasação
                em.close();
                emf.close();
            }else {
                //limpa todos os campos exceto o cod
                txt_imovel_cnpj_const.setText("");
                txt_imovel_condominio.setText("");
                txt_imovel_area_util.setText("");
                txt_imovel_preco.setText("");
                rad_imovel_apart.setSelected(false);
                rad_imovel_casa.setSelected(false);
                rad_imovel_sim.setSelected(false);
                rad_imovel_nao.setSelected(false);
            }
        }
    }//GEN-LAST:event_txt_imovel_codFocusLost

    void limparCampos()
    {
        //limpa todos os campos do Formulario_imovel
        txt_imovel_cod.setText("");
        txt_imovel_cnpj_const.setText("");
        txt_imovel_condominio.setText("");
        txt_imovel_area_util.setText("");
        txt_imovel_preco.setText("");
        rad_imovel_apart.setSelected(false);
        rad_imovel_casa.setSelected(false);
        rad_imovel_sim.setSelected(false);
        rad_imovel_nao.setSelected(false);

        //aponta cursor para o campo cod
        //txt_imovel_cod.requestFocus();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btn_imovel_excluir;
    private javax.swing.JButton btn_imovel_limpar;
    private javax.swing.JButton btn_imovel_salvar;
    private javax.swing.JLabel lab_imovel_area_util;
    private javax.swing.JLabel lab_imovel_cnpj_const;
    private javax.swing.JLabel lab_imovel_cod;
    private javax.swing.JLabel lab_imovel_condominio;
    private javax.swing.JLabel lab_imovel_preco;
    private javax.swing.JLabel lab_imovel_tipo;
    private javax.swing.JLabel lab_imovel_vendido;
    private javax.swing.ButtonGroup radGroup_imovel_tipo;
    private javax.swing.ButtonGroup radGroup_imovel_vendido;
    private javax.swing.JRadioButton rad_imovel_apart;
    private javax.swing.JRadioButton rad_imovel_casa;
    private javax.swing.JRadioButton rad_imovel_nao;
    private javax.swing.JRadioButton rad_imovel_sim;
    private javax.swing.JTextField txt_imovel_area_util;
    private javax.swing.JTextField txt_imovel_cnpj_const;
    private javax.swing.JTextField txt_imovel_cod;
    private javax.swing.JTextField txt_imovel_condominio;
    private javax.swing.JTextField txt_imovel_preco;
    // End of variables declaration//GEN-END:variables

}
